<?php

// +----------------------------------------------------------------------
// | Author: 逯佳 后台文章发布，列表 资源发布，列表
// +----------------------------------------------------------------------





namespace Admin\Controller;
use Think\Controller;
class IndexController extends Controller {

	//检测是否登录 以及是否管理员 
	public function checkAdmin(){
		$rsu = checkLogin();
		if ($rsu) {
			$admin = M('user')->where(['username'=>cookie('user')])->find()['is_admin'];
			if ($admin){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	//返回所有栏目
	public function getCat(){
		$catall = D('Cat')->getPre();
		return $catall;
	}
	//返回所有文章供ajax使用
	public function getArt(){
		$artall = M('Art')->field('art_id,catname,region,title,year,type,update_time,status')->join('cat on art.cat_id=cat.cat_id')->order('art_id desc')->select();
		$this->ajaxReturn($artall,'json');
	}
	//返回所有资源供ajax使用
	public function getResource(){
		$rsoall = M('resource')->field('r_id,art.art_id,title,num,status,title,pubtime')->join('art on resource.art_id = art.art_id')->order('art_id desc,num')->select();
		$this->ajaxReturn($rsoall,'json');
	}
	//后台主页 
	public function index(){
		$rsu = $this->checkAdmin();
		if ($rsu) {
			$catall = $this->getcat();
			$this->assign(['catall'=>$catall]);
			$this->display();
		}else{
			$this->redirect('/home');
		}
	}
	/**
	 * 文章添加 数据库操作
	 * @return ajax返回结果 添加成功 or 错误信息
	 */
	public function addArt(){
		//实例化art表
		$art = M('art');
		$type = M('type');
		//自动创建数据
		$art->create(I('post.'));
		//更新时间
		$art->update_time = time();
		//获取cat_id
		$cat_id = M('cat')->field('parent_id')->where(['cat_id'=>$art->class])->find()['parent_id'];
		if ($cat_id == 0) {
			$art->cat_id = $art->class;
		}else{
			$art->cat_id = $cat_id;
		}
		//记录栏目 方便添加类型时添加
		$cat = $art->cat_id;
		$result = $art->add();
		if (is_numeric($result)) {
			$types = explode(' ',I('type'));
			foreach ($types as $v) {
				$rsu = $type->where(['type'=>$v,'cat_id'=>$cat])->find();
				if (empty($rsu)) {
					$data['type'] = $v;
					$data['cat_id'] = $cat;
					$type->add($data);
				}	
			}
			$this->ajaxReturn('添加成功','eval');	
		}else{
			$this->ajaxReturn($result,'eval');
		}	
		
	}
	/**
	 * 资源添加 数据库操作
	 * @return ajax返回结果 添加成功 or 错误信息
	 */
	public function addResource(){
		$rsom = M('resource');
		$rsom->create(I('post.'));
		$rsom->pubtime = time();		
		$result = $rsom->add();
		if (is_numeric($result)) {
			$artm = M('art');
			$data['status'] = I('status');
			$data['sum'] = I('num');
			$data['update_time'] = time();
			if ($artm->where(['art_id'=>I('art_id')])->save($data) == 1) {
				$this->ajaxReturn('添加成功','eval');
			}else{
				$rsom->where(['r_id'=>$result])->delete();
				$this->ajaxReturn('添加失败','eval');
			}
		}else{
			$this->ajaxReturn($result,'eval');
		}	
	}
	


}